package com.springboot.springbootweb.copyfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 自制简易复制增量更新文件
 *
 * @author hs
 */
public class CopyFile {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//-HH-mm
        String source = "C:\\Users\\Somust\\eclipse-workspace\\kwm\\WebContent";
        //String source = "C:\\Users\\Somust\\eclipse-workspace\\kwm_zs_branch\\WebContent";        
        String destin = "C:\\Users\\Somust\\Desktop\\更新文件\\" + sdf.format(new Date()) + "\\WebContent";
        deleteDir(new File(destin));//删除文件夹
        int i = copyFile(0, "2021-09-24 11:00:00", "", source, destin);
        System.out.println("操作完成，共更新" + i + "个文件");
    }

    /**
     * 复制增量更新文件
     *
     * @param count  总文件个数
     * @param begin  开始时间 yyyy-MM-dd HH:mm:ss
     * @param end    结束时间 yyyy-MM-dd HH:mm:ss 传空值为当前时间
     * @param source 源目录
     * @param destin 复制目录
     * @return
     */
    public static int copyFile(int count, String begin, String end, String source, String destin) {
        try {
            Date beginDate = Optional.ofNullable(begin).map(item -> parse(item)).orElse(new Date());
            Date endDate = Optional.ofNullable(end).map(item -> parse(item)).orElse(new Date());
            File path1 = new File(source);
            File path2 = new File(destin);

            if (path1.exists()) {
                File[] items = path1.listFiles();
                FileInputStream fis = null;
                FileOutputStream fos = null;

                for (File item : items) {
                    // 如果是文件且更新时间在时间段内才进行复制
                    if (item.isFile()) {
                        long time = item.lastModified();
                        if (time >= beginDate.getTime() && time <= endDate.getTime() && !noCopy(item.getName())) {
                            // Create destination
                            if (!path2.exists()) {
                                path2.mkdirs();
                            }
                            fis = new FileInputStream(item);
                            fos = new FileOutputStream(path2 + File.separator + item.getName());
                            System.out.println("path:" + path2 + File.separator + item.getName());
                            byte[] b = new byte[1024];
                            for (int i = 0; (i = fis.read(b)) != -1; ) {
                                fos.write(b, 0, i);
                                fos.flush();
                            }

                            fos.close();
                            fis.close();
                            count++;
                        }
                    } else {
                        count = copyFile(count, begin, end, item.getPath(), path2 + File.separator + item.getName());
                    }
                }
            } else {
                System.out.println("source path:" + source + " is not exists!");
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 不需要更新的文件
     *
     * @param fileName
     * @return
     */
    private static boolean noCopy(String fileName) {
        List<String> noCopys = new ArrayList<String>(Arrays.asList("sys.properties", "log4j.properties"));
        if (noCopys.contains(fileName)) {
            return true;
        } else {
            return false;
        }
    }

    private static Date parse(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            return new Date();
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();//递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * 删除空目录
     *
     * @param dir 将要删除的目录路径
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }
}
